//
//  AppDelegate.swift
//  微博08
//
//  Created by 123 on 16/2/29.
//  Copyright © 2016年 Tsr. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        setupAppearance()
        
        let account = LTUserAccountViewModel.sharedInstance.userAccount
        print("在appDelegate: \(account)")
   
        // 1.创建window
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        
        // 2.设置window的跟控制器
        window?.rootViewController = defaultController()
        
        
        // 3.设置成为主窗口,并显示
        window?.makeKeyAndVisible()
        
        
    
        
        return true
    }
    
    private func setupAppearance() {
        
        // 设置导航栏按钮的外观颜色
        let item = UIBarButtonItem.appearance()
        
        item.tintColor = UIColor.orangeColor()
    }
    
    // 默认登录控制器
    private func defaultController() -> UIViewController {
        if !LTUserAccountViewModel.sharedInstance.userLogin {
            return LTMainController()
        }
        // 用户已经登录
        return isNewVresion() ? LTNewFeatureViewController() : LTWelcomeViewController()
    }
    
    // 目标控制器:目标控制器有2个
    /**
    跳转界面
    
    - parameter isMain: true: LTMainViewController, false: LTWelcomeViewController
    */
    private func switchRootViewController(isMain: Bool) {
        window?.rootViewController = isMain ? LTMainController() : LTWelcomeViewController()
    }
    
    /**
     跳转界面
     
     - parameter isMain: true: LTMainViewController, false: LTWelcomeViewController
     */
     
    class func outSwitchRootViewController(isMain: Bool) {
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        appDelegate.switchRootViewController(isMain)
    }
    
    // 判是否是新版本
    private func isNewVresion() -> Bool {
        // 1.获取当前运行的版本
        let version = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        
        // 2.获取上一次运行的版本
        let sandboxVersionKey = "sandboxVersionKey"
        let sandboxVersion = NSUserDefaults.standardUserDefaults().stringForKey(sandboxVersionKey)
        
        // 3.对比
        let newVersion = version != sandboxVersion
        
        // 4.新版本的话,保存到偏好设置中
        if newVersion {
            // 是新版本的话,将保存起来
            NSUserDefaults.standardUserDefaults().setObject(version, forKey: sandboxVersionKey)
            // 立刻同步
            NSUserDefaults.standardUserDefaults().synchronize()
        }
        
        // 5.返回比较的结果
        return newVersion
    }
}

